package com.dxj1992.controller.admin.auth;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dxj1992.entity.AdminUsers;
import com.dxj1992.service.IAdminUsersService;
import com.dxj1992.utils.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
@RequestMapping("/admin")
@Slf4j
public class LoginController {

    @Autowired
    private IAdminUsersService adminUsersService;

    @GetMapping("/login")
    public String login() {
        return "admin/auth/login";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("admin");
        return "redirect:admin/login";
    }

    @PostMapping("/doLogin")
    @ResponseBody
    public CommonResult doLogin(HttpServletRequest request, String username, String password, String validateCode) {

        HttpSession session = request.getSession();
        if (StrUtil.isBlank(validateCode) || !validateCode.equals(session.getAttribute("circleCaptchaCode"))) {
            session.removeAttribute("circleCaptchaCode");
            return CommonResult.failed("验证码不正确");
        }
        System.out.println(SecureUtil.md5(username + password));
        String str =  "172eee54aa664e9dd0536b063796e54e";
        AdminUsers adminUsers = adminUsersService.getOne(Wrappers.<AdminUsers>lambdaQuery().eq(AdminUsers::getName, username).eq(AdminUsers::getPassword, str), false);
        if (Objects.isNull(adminUsers)){
            return CommonResult.failed("账号或密码错误");
        }
        session.setAttribute("admin", adminUsers);
        return CommonResult.success("登录成功");
    }
}
